const {
	reqGet,
	reqPost,
} = require('@utils/request')
const {
	$U_UserInfo,
} = require('@utils/storage')
const {
	setFormEdit,
	setBtnEdit,
	randomId,
} = require('./api-utils')
const {
	diffHistory,
} = require('./api-utils-history')
const {
	loadProjectData,
	loadAPIDetail,
} = require('./api-data')

module.exports = {

	/**
	 * 编辑按钮
	 * @return {[type]} [description]
	 */
	editMethod() {
		let {
			store
		} = this
		let userInfo = $U_UserInfo()
		let apiComp = this
		$.messager.progress()
		reqGet('/ult/project/locked', {
			project_id: store.projectId,
			locked_user: `${userInfo.realname}(${userInfo.nickname})`,
		}).then(result => {
			let {
				is_locked,
				locked_user,
			} = result
			$.messager.progress('close')
			if (is_locked == 1) {
				alert(`${locked_user} 正在编辑！！！`)
				return false
			}
			loadProjectData(apiComp, store.projectId);
		})
	},

	/**
	 * 取消按钮
	 * @return {[type]} [description]
	 */
	cancelMethod() {
		let {
			store,
		} = this
		let apiComp = this
		$.messager.confirm({
			title: '提示',
			msg: '都白干了，确认放弃保存？',
			fn(r) {
				if (r) {
					reqGet('/ult/project/unlock', {
						project_id: store.projectId,
					}).then(result => {
						apiComp.store._currentCheckApiDetail = null
						loadProjectData(apiComp, store.projectId);
					})
				}
			}
		});
	},

	/**
	 * 快存版本号最后一位递增
	 * @param  {[type]} apiComp [description]
	 * @return {[type]}         [description]
	 */
	quickSaveMethod() {
		console.log('history', this.store.history)
		saveData.call(this)
	},

	/**
	 * 保存，可选择版本号增加
	 * @return {[type]} [description]
	 */
	saveMethod() {
		let {
			saveFormVersion,
			saveFormIntro,
			saveDialog,
		} = this
		saveData.call(this, {
			version: saveFormVersion.combobox('getValue'),
			description: saveFormIntro.textbox('getValue'),
		})
		saveDialog.dialog('close')
	},

	/**
	 * 保存弹出版本信息对话框
	 * @return {[type]} [description]
	 */
	showSaveDialogMethod() {
		let {
			store,
			saveDialog,
			saveFormVersion,
			saveFormIntro,
		} = this
		let editProjectData = store.editProjectData
		let version = editProjectData.version
		let versionData = []
		let version1 = version.replace(/^\d*/, val => {
			val = parseInt(val)
			val += 1
			return val
		})
		let version2 = version.replace(/\.[\d]+\./, val => {
			val = parseInt(val.replace(/\./g, ''), '')
			val += 1
			return `.${val}.`
		})
		let version3 = version.replace(/\d*$/, val => {
			val = parseInt(val)
			val += 1
			return val
		})
		versionData.push({
			text: `${version} -->> ${version1}`,
			value: version1,
		})
		versionData.push({
			text: `${version} -->> ${version2}`,
			value: version2,
		})
		versionData.push({
			text: `${version} -->> ${version3}`,
			value: version3,
		})
		saveFormVersion.combobox('loadData', versionData)
		saveFormVersion.combobox('setValue', version3)
		saveDialog.dialog('open')
	},

}

function saveData(params = {}) {
	let {
		version,
		description = '快存',
	} = params
	let {
		store,
		reqParamsComp,
		resParamsComp,
		formContentType,
		formPath,
		formMethod,
		formIntro,
		alertDialog,
		alertText,
	} = this
	if (!store.isLock)
		return false
	if (!store.isSave)
		return false
	let apiComp = this
	let editProjectData = store.editProjectData
	let userInfo = $U_UserInfo()
	store.version = version = version || editProjectData.version.replace(/\d*$/, val => {
		val = parseInt(val)
		val += 1
		return val
	})
	editProjectData.version = version
	let reqCurrent = store.reqCurrent
	let resCurrent = store.resCurrent
	let requestData = reqParamsComp.treegrid('getData')
	let responseData = resParamsComp.treegrid('getData')
	if (reqCurrent.editRow && reqCurrent.editRow._treeId_)
		reqParamsComp.treegrid('endEdit', reqCurrent.editRow._treeId_)
	if (resCurrent.editRow && resCurrent.editRow._treeId_)
		resParamsComp.treegrid('endEdit', resCurrent.editRow._treeId_)
	if (store._currentEditApiDetail && store._currentEditApiDetail.attributes) {
		let moduleId = store._currentEditApiDetail.attributes.moduleId
		let apiId = store._currentEditApiDetail.id
		let currentEditAPI = editProjectData.modules[moduleId].apis[apiId]
		let path = formPath.textbox('getText');
		let intro = formIntro.textbox('getText');
		formPath.textbox('setValue', path);
		formIntro.textbox('setValue', intro);
		// 去除未命名的请求参数
		requestData = requestData.filter(val => {
			return val && val.name
		});
		// 去除未命名的响应参数
		responseData = responseData.filter(val => {
			return val && val.name
		});
		currentEditAPI.attributes.contentType = formContentType.combobox('getValue');
		currentEditAPI.attributes.method = formMethod.combobox('getValue');
		currentEditAPI.attributes.path = path;
		currentEditAPI.attributes.intro = intro;
		currentEditAPI.attributes.requestParameterList = requestData;
		currentEditAPI.attributes.responseParameterList = responseData;
		// currentEditAPI.attributes.requestParameterList = JSON.stringify(requestData);
		// currentEditAPI.attributes.responseParameterList = JSON.stringify(responseData);
	}
	let desc = {
		info: description,
		history: diffHistory.call(store),
	}
	$.messager.progress({
		text: '保存中。。。'
	})
	reqPost('/ult/api/save', {
		project_id: store.projectId,
		project_data: JSON.stringify(editProjectData),
		version,
		user_id: userInfo.id,
		edit_user: `${userInfo.realname}(${userInfo.nickname})`,
		description: JSON.stringify(desc),
	}).then(result => {
		if (!result.affectedRows || !result.insertId) {
			alertDialog.dialog('setTitle', '提示')
			alertText.textbox('setValue', JSON.stringify(result, null, 5) || "什么都没返回！");
			alertDialog.dialog('open');
			$.messager.progress('close')
			return false
		}
		store.isLock = false
		setFormEdit(apiComp)
		setBtnEdit(apiComp)
		reqParamsComp.treegrid('loadData', requestData)
		resParamsComp.treegrid('loadData', responseData)
		$.messager.progress('close')
		$.messager.alert({
			title: '提示',
			msg: '保存成功！'
		})
	})
}